<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Avatar, Message, Key } from '@element-plus/icons-vue'
import { useAuthStore } from '@/store'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)
const authStore = useAuthStore()

// 登录方式选择（密码/验证码）
const loginType = ref('password') // 默认密码登录
const isPasswordLogin = computed(() => loginType.value === 'password')

// 表单数据 - 密码登录
const loginForm = reactive({
  username: '',
  password: '',
})

// 表单数据 - 验证码登录
const codeLoginForm = reactive({
  email: '',
  verifyCode: '',
  rememberMe: false  // 添加记住我选项
})

// 验证码相关
const countdown = ref(0)
const isSending = ref(false)
let timer = null

// 表单验证规则 - 密码登录
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度应在5-20个字符之间', trigger: 'blur' }
  ]
}

// 表单验证规则 - 验证码登录
const codeLoginRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

// 切换登录方式
const switchLoginType = (type) => {
  loginType.value = type
}

// 发送验证码
const sendVerifyCode = async () => {
  // 验证邮箱格式
  if (!codeLoginForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailPattern.test(codeLoginForm.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }
  
  isSending.value = true
  try {
    // 调用发送验证码API
    await authStore.sendCode(codeLoginForm.email)
    
    // 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isSending.value = false
      }
    }, 1000)
  } catch (error) {
    isSending.value = false
  }
}

// 登录按钮的点击事件
const handleLogin = async () => {
  const formRef = loginFormRef.value
  if (!formRef) return
  
  // 根据登录类型选择不同的表单验证和登录逻辑
  if (isPasswordLogin.value) {
    // 密码登录
    await formRef.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        
        try {
          // 使用 auth store 进行登录
          const success = await authStore.loginUser(
            loginForm.username,
            loginForm.password
          )
          
          if (success) {
            // 登录成功，跳转到首页
            router.push('/home')
          }
        } finally {
          loading.value = false
        }
      } else {
        console.log('验证失败', fields)
      }
    })
  } else {
    // 验证码登录
    await formRef.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        
        try {
          // 使用 auth store 进行验证码登录
          const userData = {
            email: codeLoginForm.email,
            code: codeLoginForm.verifyCode
          }
          
          const success = await authStore.loginWithEmailCode(userData)
          
          if (success) {
            // 登录成功，跳转到首页
            router.push('/home')
          }
        } finally {
          loading.value = false
        }
      } else {
        console.log('验证失败', fields)
      }
    })
  }
}

// 忘记密码
const handleForgotPassword = () => {
  router.push('/forgot-password')
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="title-icon">
          <el-icon :size="30" color="#c20c0c"><Avatar /></el-icon>
        </div>
        <h1>欢迎回来</h1>
        <div class="title-decoration"></div>
        <p>登录您的账号，体验更多精彩功能</p>
      </div>
      
      <!-- 登录方式选择器 -->
      <div class="login-type-selector">
        <div 
          class="login-type-option" 
          :class="{ active: isPasswordLogin }"
          @click="switchLoginType('password')"
        >
          密码登录
        </div>
        <div 
          class="login-type-option" 
          :class="{ active: !isPasswordLogin }"
          @click="switchLoginType('code')"
        >
          验证码登录
        </div>
      </div>
      
      <!-- 密码登录表单 -->
      <el-form
        v-if="isPasswordLogin"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            @keydown.enter="handleLogin"
            show-password
          />
        </el-form-item>
        
        <div class="form-options">
          <el-checkbox class="custom-checkbox">记住我</el-checkbox>
          <a href="#" @click="handleForgotPassword" class="forgot-link">忘记密码?</a>
        </div>

        <el-button 
          type="danger" 
          class="login-button" 
          @click="handleLogin" 
          :loading="loading"
        >
          登录
        </el-button>
      </el-form>
      
      <!-- 验证码登录表单 -->
      <el-form
        v-else
        ref="loginFormRef"
        :model="codeLoginForm"
        :rules="codeLoginRules"
        class="login-form"
      >
        <el-form-item prop="email">
          <el-input
            v-model="codeLoginForm.email"
            placeholder="请输入邮箱"
            :prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="verifyCode">
          <div class="code-input-group">
            <el-input
              v-model="codeLoginForm.verifyCode"
              placeholder="请输入验证码"
              :prefix-icon="Key"
              @keydown.enter="handleLogin"
            />
            <el-button 
              class="code-button" 
              :disabled="isSending || countdown > 0"
              @click="sendVerifyCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 添加表单选项 -->
        <div class="form-options">
          <el-checkbox v-model="codeLoginForm.rememberMe" class="custom-checkbox">记住我</el-checkbox>
          <a href="#" class="forgot-link">收不到验证码？</a>
        </div>

        <el-button 
          type="danger" 
          class="login-button" 
          @click="handleLogin" 
          :loading="loading"
        >
          登录
        </el-button>
      </el-form>

      <div class="register-link">
        还没有账号？<router-link to="/register">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 420px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 登录方式选择器样式 */
.login-type-selector {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.login-type-option {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  position: relative;
  transition: all 0.3s;
}

.login-type-option.active {
  color: #c20c0c;
}

.login-type-option.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 20%;
  width: 60%;
  height: 2px;
  background-color: #c20c0c;
}

.login-type-option:hover {
  color: #c20c0c;
}

/* 验证码输入框组样式 */
.code-input-group {
  display: flex;
  gap: 10px;
  width: 100%; /* 确保占据整行宽度 */
}

.code-input-group .el-input {
  flex: 1;
}

.code-button {
  width: 120px;
  flex-shrink: 0; /* 防止按钮被压缩 */
  font-size: 12px;
  padding: 0 5px;
  background-color: #fff;
  border-color: #d9d9d9;
  color: #606266;
}

.code-button:hover, .code-button:focus {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #c20c0c;
  transition: all 0.3s;
}

.code-button:disabled {
  background-color: #f5f5f5;
  border-color: #e4e7ed;
  color: #c0c4cc;
}

.login-header {
  text-align: center;
  margin-bottom: 35px;
  position: relative;
}

.title-icon {
  background-color: #fef0f0;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto 15px;
  box-shadow: 0 3px 6px rgba(194, 12, 12, 0.1);
}

.login-header h1 {
  font-size: 28px;
  margin-bottom: 15px;
  color: #333;
  font-weight: 600;
}

.title-decoration {
  width: 40px;
  height: 3px;
  background-color: #c20c0c;
  margin: 0 auto 15px;
  border-radius: 3px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form :deep(.el-input__wrapper) {
  padding: 1px 11px;
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #c20c0c inset;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
}

.custom-checkbox {
  --el-checkbox-font-size: 14px;
  --el-checkbox-checked-text-color: #333;
  /* --el-checkbox-checked-icon-color: #c20c0c; */
  --el-checkbox-checked-bg-color: #fff;
  --el-checkbox-checked-border-color: #c20c0c;
}

.forgot-link {
  color: #c20c0c;
  text-decoration: none;
}

.forgot-link:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 12px;
  margin-bottom: 20px;
  background-color: #c20c0c;
  border-color: #c20c0c;
}

.login-button:hover, .login-button:focus {
  background-color: #a60a0a;
  border-color: #a60a0a;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #c20c0c;
  text-decoration: none;
}
</style> 